import 'dart:async';

import 'package:card_swiper/card_swiper.dart';
import 'package:distribution_mall_flutter/constant/constant.dart';
import 'package:distribution_mall_flutter/entity/goods/detail/goods_detail_entity.dart';
import 'package:distribution_mall_flutter/ext/toast_ext.dart';
import 'package:distribution_mall_flutter/pages/goods/product_details/widgets/product_details_content_swiper/widget/flick_portrait_controls.dart';
import 'package:distribution_mall_flutter/pages/goods/product_details/widgets/product_details_content_swiper/product_details_content_provider.dart';
import 'package:distribution_mall_flutter/pages/goods/product_details/widgets/product_nav.dart';
import 'package:distribution_mall_flutter/provider/goods/product_details.dart';
import 'package:distribution_mall_flutter/router/router.gr.dart';
import 'package:distribution_mall_flutter/utils/debug.dart';
import 'package:flick_video_player/flick_video_player.dart';
import 'package:flutter/foundation.dart';
import 'package:hive/hive.dart';
import 'package:video_player/video_player.dart';
import 'package:extended_image/extended_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:skeletonizer/skeletonizer.dart';

import 'widget/flick_video_with_controls.dart';

class ProductSwiperInfo {
  String imageUrl;
  String? videoUrl;

  ProductSwiperInfo({required this.imageUrl, this.videoUrl});
}
class SwiperPlayInfo{
  FlickManager? flickManager;
  ///离开时候是否还在播放中,如果是回来继续播放
  bool? skipNextIsPlaying;

  SwiperPlayInfo(this.flickManager, this.skipNextIsPlaying);
}

class ProductDetailsContentSwiper extends ConsumerStatefulWidget {
  const ProductDetailsContentSwiper({super.key});

  @override
  ConsumerState<ProductDetailsContentSwiper> createState() =>
      _ProductDetailsContentSwiperState();
}

class _ProductDetailsContentSwiperState
    extends ConsumerState<ProductDetailsContentSwiper> {
  Map<String, SwiperPlayInfo> flickManagerMap = {};

  SwiperPlayInfo? getFlickManager(String? url) {
    if (url == null) {
      return null;
    }
    if (flickManagerMap.containsKey(url)) {
      return flickManagerMap[url]!;
    } else {
      var itemManager = SwiperPlayInfo(FlickManager(
          autoPlay: false,
          videoPlayerController: VideoPlayerController.networkUrl(
            Uri.parse(url),
          )),null);
      flickManagerMap[url] = itemManager;
      return itemManager;
    }
  }

  @override
  void dispose() {
    flickManagerMap.forEach((key, value) {
      value.flickManager?.dispose();
    });
    flickManagerMap.clear();
    super.dispose();
  }

  List<ProductSwiperInfo> swiperInfo(SuInfo? suInfo) {
    if (suInfo == null) {
      return [];
    }
    return [
      ///web播放器暂时有问题
      if (!kIsWeb && suInfo.detailVideos?.isNotEmpty == true)
        ...suInfo.detailVideos!.map((e) =>
            ProductSwiperInfo(imageUrl: e.imageUrl, videoUrl: e.videoUrl)),
      if (suInfo.mainImages?.isNotEmpty == true)
        ...suInfo.mainImages!.map((e) => ProductSwiperInfo(imageUrl: e)),
    ];
  }

  @override
  Widget build(BuildContext context) {
    final mainImages = swiperInfo(ref.watch(pDetailProvider).detail?.suInfo);
    ref.listen(pDetailProvider.select((e) => e.detail?.suInfo), (pre, next) {
      if (pre == null && next != null) {
        // resize(swiperInfo(next), 0, MediaQuery.of(context).size.width);
      }
    });
    // final mainImages = [
    //   'https://test-1300597023.cos.ap-singapore.myqcloud.com/1261723707719_.pic.jpg',
    //   'https://test-1300597023.cos.ap-singapore.myqcloud.com/1271723707722_.pic.jpg',
    //   'https://test-1300597023.cos.ap-singapore.myqcloud.com/1281723707725_.pic.jpg',
    // ];

    ///获取屏幕宽度
    var width = MediaQuery.of(context).size.width;
    final productDetailsSwiperHeight =
        ref.watch(productDetailsSwiperHeightProvider(width));
    return AnimatedContainer(
      duration: const Duration(milliseconds: 100),
      margin: EdgeInsets.only(
          top: kIsWeb
              ? 0
              : (MediaQuery.of(context).padding.top -
                  // ProductNav.productNavMarginTop -
                  kToolbarHeight)),
      height: productDetailsSwiperHeight,
      child: Skeleton.replace(
          width: double.infinity,
          height: productDetailsSwiperHeight,
          child: Stack(
            children: [
              Swiper(
                // autoplay: true,
                loop: (mainImages.length) > 1,
                duration: 1500,
                // pagination: const SwiperPagination(
                //     margin: EdgeInsets.only(bottom: 18.2),
                //     builder: DotSwiperPaginationBuilder(
                //       activeColor: Colors.white,
                //       color: Color.fromRGBO(244, 244, 244, 0.84),
                //       size: 7.3,
                //       activeSize: 7.3,
                //       space: 4.5,
                //     )),
                allowImplicitScrolling: true,
                itemCount: mainImages.length,
                onIndexChanged: (index) {
                  resize(mainImages, index, width);
                },
                itemBuilder: (BuildContext context, int index) {
                  var image = mainImages[index];

                  return GestureDetector(
                    onTap: () {
                      appRouter.push(ReviewImageRoute(
                          images: mainImages.map((e) => e.imageUrl).join(','),
                          index: index));
                    },
                    child: ContentSwiperItem(
                        productSwiperInfo: image,
                        key: ValueKey(index),
                        index: index,
                        swiperPlayInfo: getFlickManager(image.videoUrl)),
                  );
                },
              ),
              Positioned(
                right: 19,
                bottom: 20,
                child: Consumer(builder: (context, ref, _) {
                  var index = ref.watch(productDetailsSwiperIndexProvider);
                  return Container(
                    decoration: BoxDecoration(
                      color: const Color(0x80000000),
                      borderRadius: BorderRadius.circular(2),
                    ),
                    padding:
                        const EdgeInsets.symmetric(vertical: 2, horizontal: 4),
                    child: Text(
                      '${index + 1}/${mainImages.length}',
                      style: const TextStyle(fontSize: 14, color: Colors.white),
                    ),
                  );
                }),
              )
            ],
          )),
    );
  }

  void resize(List<ProductSwiperInfo> mainImages, int index, double width) {
    if (!mounted) {
      return;
    }
    var provider = ExtendedNetworkImageProvider(mainImages[index].imageUrl);

    // 获取图片的ImageStream
    final ImageStream stream = provider.resolve(const ImageConfiguration());

    // 定义图片加载监听器
    ImageStreamListener? listener;
    listener = ImageStreamListener(
      (ImageInfo info, bool synchronousCall) {
        // 图片加载完成，获取图片的宽度和高度
        final imageSize = Size(
          info.image.width.toDouble(),
          info.image.height.toDouble(),
        );
        Future(() {
          if (mounted) {
            if (ref.read(productDetailsSwiperIndexProvider) == index) {
              ref
                  .read(productDetailsSwiperHeightProvider(width).notifier)
                  .setNewHeight(width / imageSize.width * imageSize.height);
            }
          }
        });
        stream.removeListener(listener!);
      },
      onError: (exception, stackTrace) {
        stream.removeListener(listener!);
      },
    );
    // 为ImageStream添加监听器
    stream.addListener(listener);
    ref.read(productDetailsSwiperIndexProvider.notifier).setNewData(index);
  }
}

///本来准备用来做图片加载回调,但是这样执行动作比较延后,不如onIndexChanged里写
class ContentSwiperItem extends ConsumerStatefulWidget {
  final ProductSwiperInfo productSwiperInfo;
  final int index;
  final SwiperPlayInfo? swiperPlayInfo;

  const ContentSwiperItem({
    super.key,
    required this.productSwiperInfo,
    required this.index,
    this.swiperPlayInfo,
  });

  @override
  ConsumerState<ContentSwiperItem> createState() => _ContentSwiperItemState();
}

class _ContentSwiperItemState extends ConsumerState<ContentSwiperItem> {

  @override
  Widget build(BuildContext context) {
    ref.listen(productDetailsSwiperIndexProvider, (pre, next) {
      ///离开时候
      if (pre == widget.index && next != widget.index) {
        if (widget.swiperPlayInfo?.flickManager?.flickVideoManager?.isPlaying == true) {
          widget.swiperPlayInfo?.skipNextIsPlaying = true;
          widget.swiperPlayInfo?.flickManager?.flickVideoManager?.videoPlayerController?.pause();
        }
      } else if (next == widget.index) {
        ///来到时候
        if (widget.swiperPlayInfo?.skipNextIsPlaying == true) {
          widget.swiperPlayInfo?.skipNextIsPlaying = false;
          widget.swiperPlayInfo?.flickManager?.flickVideoManager?.videoPlayerController?.play();
        }
      }
    });
    Widget image = ExtendedImage.network(
      widget.productSwiperInfo.imageUrl,
      fit: BoxFit.fill,
      enableLoadState: false,
    );
    return widget.swiperPlayInfo == null
        ? image
        : FlickVideoPlayer(
            flickManager: widget.swiperPlayInfo!.flickManager!,
            flickVideoWithControls: EpFlickVideoWithControls(
              backgroundColor: Colors.black,
              cover: Positioned.fill(child: image),
              textStyle: const TextStyle(
                color: Colors.black,
              ),
              iconThemeData: const IconThemeData(
                color: Colors.black,
                size: 20,
              ),
              controls: EpFlickPortraitControls(
                progressBarSettings: FlickProgressBarSettings(
                    // playedColor: Colors.red,
                    // handleColor: Colors.red,
                    // backgroundColor: Colors.grey
                    ),
              ),
            ));
  }
}
